package com.msk.common.wechatV3.util;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.msk.common.utils.DateUtil;
import com.msk.common.utils.StringUtils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.OutputStream;
import java.util.Hashtable;

/**
 * @desc: 二维码公共类
 * @author: zlf
 * @date: 2021-09-13 19:49
 **/
public class QrCodeUtil {

    //编码格式,采用utf-8
    private static final String UNICODE = "utf-8";
    //图片格式
    private static final String FORMAT = "png";
    //二维码宽度像素pixels数量
    private static final int QRCODE_WIDTH = 300;
    //二维码高度像素pixels数量
    private static final int QRCODE_HEIGHT = 300;
    //LOGO宽度像素pixels数量
    private static final int LOGO_WIDTH = 100;
    //LOGO高度像素pixels数量
    private static final int LOGO_HEIGHT = 100;

    /**
     * 生成二维码图片，直接输出到OutputStream
     * @param content
     * @param output
     * @throws Exception
     */
    public static void encode(String content, OutputStream output) throws Exception {

        Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); // 内容所使用字符集编码
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        hints.put(EncodeHintType.MARGIN, 1);

        BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, QRCODE_WIDTH, QRCODE_HEIGHT, hints);
        // 生成二维码
        MatrixToImageWriter.writeToStream(bitMatrix, FORMAT, output);
    }

    /**
     * 生成带logo二维码图片，直接输出到OutputStream
     * @param content
     * @param logoPath
     * @param output
     * @throws Exception
     */
    public static void encode(String content, String logoPath, OutputStream output)
            throws Exception {
        BufferedImage image = QrCodeUtil.createImage(content, logoPath);
        ImageIO.write(image, FORMAT, output);
    }

    /**
     * 生成二维码图片
     * @param content
     * @param logoPath
     * @return
     * @throws Exception
     */
    public static BufferedImage createImage(String content, String logoPath) throws Exception {
        Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); // 内容所使用字符集编码
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        hints.put(EncodeHintType.MARGIN, 1);

        BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, QRCODE_WIDTH, QRCODE_HEIGHT, hints);
        int width = bitMatrix.getWidth();
        int height = bitMatrix.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
            }
        }
        if (StringUtils.isBlank(logoPath)) {
            return image;
        }
        // 插入图片
        QrCodeUtil.insertImage(image, logoPath);
        return image;
    }

    /**
     * 在图片上插入LOGO
     * @param source
     * @param logoPath
     * @throws Exception
     */
    private static void insertImage(BufferedImage source, String logoPath) throws Exception {
        File file = new File(logoPath);
        if (!file.exists()) {
            throw new Exception("logo file not found.");
        }
        Image src = ImageIO.read(new File(logoPath));
        int width = src.getWidth(null);
        int height = src.getHeight(null);
        if (width > LOGO_WIDTH) {
            width = LOGO_WIDTH;
        }
        if (height > LOGO_HEIGHT) {
            height = LOGO_HEIGHT;
        }
        Image image = src.getScaledInstance(width, height, Image.SCALE_SMOOTH);
        BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics g = tag.getGraphics();
        g.drawImage(image, 0, 0, null); // 绘制缩小后的图
        g.dispose();
        src = image;
        // 插入LOGO
        Graphics2D graph = source.createGraphics();
        int x = (QRCODE_WIDTH - width) / 2;
        int y = (QRCODE_HEIGHT - height) / 2;
        graph.drawImage(src, x, y, width, height, null);
        Shape shape = new RoundRectangle2D.Float(x, y, width, width, 6, 6);
        graph.setStroke(new BasicStroke(3f));
        graph.draw(shape);
        graph.dispose();
    }

    /**
     * 生成带logo的二维码图片，保存到指定的路径
     * @param content 二维码内容
     * @param logoPath logo图片地址
     * @param destPath 生成图片的存储路径
     * @return
     * @throws Exception
     */
    public static String save(String content, String logoPath, String destPath) {
        String filePath = null;
        try {
            BufferedImage image = QrCodeUtil.createImage(content, logoPath);
            if (StringUtils.isEmpty(destPath)) {
                destPath = System.getProperty("java.io.tmpdir");
            }
            File file = new File(destPath);
            if (!file.exists()) {
                file.mkdirs();
            }
            String fileName = DateUtil.currentFileDatetime() + "." + FORMAT.toLowerCase();
            if (!destPath.endsWith(File.separator)) {
                destPath = destPath + File.separator;
            }
            File targetFile = new File(destPath + fileName);
            ImageIO.write(image, FORMAT, targetFile);
            filePath = targetFile.getPath();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return filePath;
    }
}
